package com.ebocy.hammer.core.handler;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import com.ebocy.hammer.core.log.EbocyLogManager;
import com.ebocy.hammer.core.message.AbstractC2SMessage;

/**
 *
 *2012-3-12@author yangshaobo
 */
public class HandlerManager {
	private static Logger logger = EbocyLogManager.getSystemLogger();
	private static Map<Short, IMessageHandler> handlerMap = new HashMap<Short, IMessageHandler>();

	/**
	 * 处理器注册
	 *
	 * @param handler
	 */
	public static void registerHandler(IMessageHandler handler) {
		short[] messageCodes = handler.getMessageCodes();
		for (short messageCode : messageCodes) {
			if (handlerMap.containsKey(messageCode)) {
				logger.error("该消息号=" + messageCode + "已经注册过了！" + handlerMap.get(messageCode).getClass() + "****" + handler.getClass());
				System.exit(0);
			}
			handlerMap.put(messageCode, handler);
		}
	}

	/**
	 * 消息处理
	 */
	public static void resolveMessage(AbstractC2SMessage message, IoSession ioSession) {
		short messageCode = message.getMessageCode();
		IMessageHandler handler = handlerMap.get(messageCode);
		if (handler == null) {
			logger.info("该消息号=" + messageCode + "没有注册！" + handlerMap.get(messageCode).getClass() + "****");
		} else {
			handler.resolve(message, ioSession);
		}

	}
}
